from django.http import HttpResponse
from django.http import HttpRequest
import time
from Response.Resp import Resp
from Model.models import Comment
from utils.configreader import Reader
import json


class ContactUs(object):
    contact_img_path = Reader.getConfig('imgup', 'contact_img_path')

    # 以当前时间戳生成文件名
    def GenerateFileName(self) -> str:
        return str(int(time.time()))

    # 联系我们的图片上传
    @classmethod
    def GetImg(self, request: HttpRequest) -> HttpResponse:
        try:
            if request.method == 'GET':
                pass
            elif request.method == 'POST':
                file = request.FILES.get('file', None)
                # file_name = file.name
                # 先创建一个文件夹然后将ZIP保存到该文件件里面
                random_name = self.GenerateFileName(self)
                img_url = self.contact_img_path + random_name+".png"
                
                # 保存图片
                # wb  以二进制形式写入
                with open(img_url, "wb") as f:
                     # 写入字节流
                    f.write(file.file.read())
                f.close()

                return Resp.RightResp({
                    'rescode': 200,
                    'imgurl': img_url,
                })
        except Exception as e:
            print(repr(e))
            return Resp.ErrorResp({
                'rescode': 400,
                'msg': str(e)
            })

    # 联系我们的表单提交

    @classmethod
    def GetCommentDetail(self, request: HttpRequest) -> HttpResponse:
        try:
            if request.method == 'GET':
                pass
            elif request.method == 'POST':
                json_data = json.loads(request.body)
                Comment.objects.create(
                    send_person=json_data['person'],
                    email=json_data['email'],
                    detail=json_data['detail'],
                    img=json_data['imgurl']
                )
                return Resp.RightResp({
                    'rescode': 200
                })
        except Exception as e:
            print(repr(e))
            return Resp.ErrorResp({
                'msg': str(e),
                'rescode': 400
            })
